<template>
  <div class="container">
    <el-autocomplete clearable v-model="newValue" :fetch-suggestions="querySearch" :placeholder="placeholder" @select="handleInputSelect" style="width: 100%"></el-autocomplete>
  </div>
</template>

<script>
export default {
  name: 'AutoComplete',
  props: {
    value: {
      type: String,
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      restaurants: [],
    }
  },
  computed: {
    newValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      },
    },
  },
  mounted() {},
  destroyed() {},
  methods: {
    querySearch(queryString, cb) {
      let result = []
      const storage = localStorage.getItem('form_input_history_' + this.name)
      if (storage) {
        result = JSON.parse(storage)
      }
      this.restaurants = result
      cb(queryString ? this.restaurants.filter(this.createFilter(queryString)) : this.restaurants)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1
      }
    },
    // 保存输入纪录
    setQuerySearchItem() {
      let result = []
      const storage = localStorage.getItem('form_input_history_' + this.name)
      if (storage) {
        result = JSON.parse(storage)
        result.forEach((item) => {
          if (!item.num) {
            item.num = 1
          }
        })
        let item = result.find((item) => item.value === this.newValue)
        if (item) {
          item.num++
        } else {
          result.unshift({ value: this.newValue, num: 1 })
        }
        result.sort((a, b) => b.num - a.num)
      }
      localStorage.setItem('form_input_history_' + this.name, JSON.stringify(result.slice(0, 50)))
    },
    handleInputSelect() {},
  },
}
</script>

<style scoped lang="scss"></style>
